package front_news_api

import (
	"blog_go/models/res"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"strconv"
	"time"
)

type NewsListReq struct {
	ID   string `json:"id" form:"id" binding:"required"`
	Size int    `json:"size" form:"size"`
}

type NewsListRsp struct {
	Index    string `json:"index"`
	Title    string `json:"title"`
	HotValue string `json:"hotValue"` // 热度
	Link     string `json:"link"`
}

type httpRsp struct {
	Code int           `json:"code"`
	Data []NewsListRsp `json:"data"`
	Msg  string        `json:"msg"`
}

const newsApi = "https://api.codelife.cc/api/top/list"

func (NewsApi) NewsList(c *gin.Context) {
	var param NewsListReq
	if err := c.ShouldBindQuery(&param); err != nil {
		logrus.Error(err)
		panic(err)
	}
	client := &http.Client{
		// 设置超市时间
		Timeout: 2 * time.Second,
	}
	req, _ := http.NewRequest("GET", newsApi+"?langd=cn&id="+param.ID+"&size="+strconv.Itoa(param.Size), nil)
	req.Header.Add("Signaturekey", "U2FsdGVkX1+1qz13jyEd/4Hk9e0qHWl9frtAWUenDx8=")
	req.Header.Add("Version", "1.3.56")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	var hRsp httpRsp
	err := json.Unmarshal(body, &hRsp)
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	if hRsp.Code != 200 {
		res.FailWithMessage("拉取新闻失败", c)
		return
	}
	res.OkWithDate(hRsp.Data, c)
}
